package com.shuai.frame.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.shuai.frame.model.RpcRequest;
import com.shuai.frame.model.RpcResponse;
import com.shuai.frame.serializer.JdkSerializer;
import com.shuai.frame.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 基于JDK的动态代理
 */
public class ServiceProxy implements InvocationHandler {
    private static final Serializer serializer = new JdkSerializer();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 构造请求对象
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();

        // 序列化
        byte[] bytes = serializer.serialize(rpcRequest);
        // 发送请求
        HttpResponse execute = HttpRequest.post("localhost:8085")
                .header("Content-Type", "application/json;charset=utf8")
                .body(bytes)
                .execute();
        // 返回响应
        return serializer.deserialize(execute.bodyBytes(), RpcResponse.class).getData();
    }
}
